/**
 * Class MonitoringConsolePage.
 * 
 * @author Jean-Luc Scheefer
 */
MonitoringConsolePage.inherits(Module);
function MonitoringConsolePage() {
	var that = this;

	// Inputs module
	this.inputBeginDate = new InputDateModule({
		'id' : 'inputBeginDate',
		'label' : I18n.get('monitoring.begin.date'),
		'placeholder' : I18n.get('monitoring.begin.date'),
		'maxDate' : moment().add('days', 1),
		'value' : moment().subtract('weeks', 1),
		'onChange' : function(){
			var start = that.inputBeginDate.getMillis();
			that.inputEndDate.setMinDate(moment(start));
			if (Util.checkStringEmpty(that.inputEndDate.getValue())){
				that.inputEndDate.setValue(that.inputEndDate.maxDate);
			}
			that.inputEndDate.buildJQ();
		}
	});
	this.inputEndDate = new InputDateModule({
		'id' : 'inputEndDate',
		'label' : I18n.get('monitoring.end.date'),
		'placeholder' : I18n.get('monitoring.end.date'),
		'minDate' : moment().add('days', 1),
		'maxDate' : moment().add('days', 1),
		'value' : moment()
	});
	this.inputId = new InputTextModule({
		'id' : 'inputId',
		'label' : I18n.get('identifier'),
		'placeholder' : I18n.get('identifier'),
		'validationPattern' : ValidationPattern.VALID_INT
	});
	this.inputStatus = new InputSelectModule({
		'id' : 'inputStatus',
		'label' : I18n.get('status'),
		'defaultValue' : '',
		'options' : EnumManager.MonitoringTaskStatus
	});
	this.inputName = new InputSelectModule({
		'id' : 'inputName',
		'label' : I18n.get('type'),
		'defaultValue' : '',
		'options' : EnumManager.MonitoringTaskName
	});
	//input referrer
	this.inputReferrer = new InputReferrerModule({
		'id' : 'inputReferrer',
		'label' : I18n.get('entity'),
		'value' : UserManager.user.referrer,
		'rootReferrer' : UserManager.user.referrer,
		'mandatory' : true
	});
	
	//*********************************************************************************
	var cols = {};
	cols.idCol = new Column('id', I18n.get('monitoring.console.column.id'), '1%', true);
	cols.startDateCol = new Column('startDate', I18n.get('monitoring.console.column.startDate'), '1%', true);
	cols.startDateCol.getText = function(task) { 
		return moment(task.startDate).format('DD/MM/YY HH:mm:ss');
	};
	cols.endDateCol = new Column('endDate', I18n.get('monitoring.console.column.endDate'), '1%', true);
	cols.endDateCol.getText = function(task) {
		if (task.endDate == ""){
			return "-";
		} else {
			return moment(task.endDate).format('DD/MM/YY HH:mm:ss');
		}
	};
	cols.initiatorCol = new Column('initiator', I18n.get('monitoring.console.column.initiator'), '1%', true);
	cols.initiatorCol.getText = function(task) {
		return I18n.get('monitoring.table.initiator.' + task.initiator);
	};
	cols.messageCol = new Column('message', I18n.get('monitoring.console.column.message'), '1%', false);
	cols.statusCol = new Column('status', I18n.get('monitoring.console.column.status'), '1%', true);
	cols.statusCol.getText = function(task) {
		return '<span class="consoleStatus_' + task.status + '">' + I18n.get('monitoring.table.status.' + task.status) + '</span>';
	};
	cols.statusCol.getAlt = function(task) {
		return I18n.get('monitoring.table.status.' + task.status);
	};
	cols.fileCol = new Column('file', I18n.get('monitoring.console.column.file'), '1%', true);
	cols.seqCol = new Column('fileSequenceNumber', I18n.get('monitoring.console.column.seq'), '1%', true);
	cols.detailsCol = new Column('details', I18n.get('monitoring.console.column.details'), '1%', false);
	cols.detailsCol.getText = function(task) {
		return $('<span class="icon-eye-open "></span>').
				data('id', task.id).
				data('name', task.name).
				click(function(){
					that.displayDetails($(this).data('name'), $(this).data('id'));
				});
	};
	cols.detailsCol.getAlt = function(task) {
		return I18n.get('monitoring.console.column.seeDetails');
	};
	// collapsibles with their columns
	this.availableCollapsibles = [
	    {name : 'MANDATES_EXPORT', columns : [cols.idCol.clone().setWidth('8%'),
	                                          cols.startDateCol.clone().setWidth('14%'),
	                                          cols.endDateCol.clone().setWidth('14%'),
	                                          cols.initiatorCol.clone().setWidth('14%'),
	                                          cols.messageCol.clone().setWidth('38%'),
	                                          cols.statusCol.clone().setWidth('13%')]},
        {name : 'PAIN_008_IMPORT', columns : [cols.idCol.clone().setWidth('6%'),
                                              cols.startDateCol.clone().setWidth('14%'),
                                              cols.endDateCol.clone().setWidth('14%'),
                                              cols.initiatorCol.clone().setWidth('10%'),
                                              cols.messageCol.clone().setWidth('23%'),
                                              cols.statusCol.clone().setWidth('9%'),
                                              cols.fileCol.clone().setWidth('18%'),
                                              cols.detailsCol.clone().setWidth('6%')]},
	    {name : 'CFONB_160_IMPORT', columns : [cols.idCol.clone().setWidth('6%'),
	                                           cols.startDateCol.clone().setWidth('14%'),
	                                           cols.endDateCol.clone().setWidth('14%'),
	                                           cols.initiatorCol.clone().setWidth('10%'),
	                                           cols.messageCol.clone().setWidth('23%'),
	                                           cols.statusCol.clone().setWidth('9%'),
		                                       cols.fileCol.clone().setWidth('18%'),
		                                       cols.detailsCol.clone().setWidth('6%')]},
	    {name : 'CSV_IMPORT', columns : [cols.idCol.clone().setWidth('6%'),
	                                     cols.startDateCol.clone().setWidth('14%'),
	                                     cols.endDateCol.clone().setWidth('14%'),
	                                     cols.initiatorCol.clone().setWidth('10%'),
	                                     cols.messageCol.clone().setWidth('23%'),
	                                     cols.statusCol.clone().setWidth('9%'),
                                         cols.fileCol.clone().setWidth('18%'),
                                         cols.detailsCol.clone().setWidth('6%')]}
	];
	
	//MANDATES_EXPORT has no details so far
	this.columnSizesMapping = {
		'CFONB_160_IMPORT' : {	'lineNumber' : '12%',
								'message' : '24%',
								'details' : '64%' },
		'CSV_IMPORT' : 		 {	'lineNumber' : '12%',
								'rum' : '24%',
								'uid' : '24%',
								'message' : '64%' },
		'PAIN_008_IMPORT' :  {	'id' : '20%',
								'pid' : '20%',
								'type' : '18%',
								'message' : '42%' }
	};
	
	for (var i=0; i<this.availableCollapsibles.length; i++){
		//collapsible type
		var name = this.availableCollapsibles[i].name;
		//collapsible
		this[name] = new CollapsibleModule({
			'title' : $('<h5>' + I18n.get('monitoring.console.' + name) + '</h5>'),
			'showCollapsibleIcon' : 'prepend',
			'onUncollapse' : function(callback) { that.loadMonitoring(callback); }
		});
		//monitoring table
		this[name].table = new TableModule();
		var table = this[name].table;
		table.id = name;
		var columns = this.availableCollapsibles[i].columns;
		for (var c=0; c<columns.length; c++){
			table.columnList.push(columns[c]);
		}
	}
	
	//init
	this.monitoringLoaded = false;
}

MonitoringConsolePage.neededRoles = ["ROLE_USER", "VIEW_REPORTING", "VIEW_TASK_CONSOLE"];

MonitoringConsolePage.prototype.fillJQ = function(jQ) {
	var that = this;
	
	// Title
	jQ.append($('<h4>' + I18n.get('monitoring.console.pageTitle') + '</h4>'));
	
	// Form
	var form = $('<div class="form well row-fluid"></div>');
	jQ.append(form);
	var columnLeft = $('<div class="span6"></div>');
	columnLeft.append(this.inputBeginDate.buildJQ());
	columnLeft.append(this.inputReferrer.buildJQ());
	columnLeft.append(this.inputId.buildJQ());
	var columnRight = $('<div class="span6"></div>');
	columnRight.append(this.inputEndDate.buildJQ());
	columnRight.append(this.inputStatus.buildJQ());
	columnRight.append(this.inputName.buildJQ());
	form.append(columnLeft).append(columnRight);
	// Buttons
	var buttonRow = $('<div class="btn-row"></div>');
	form.append(buttonRow);
	var buttonSearch = $('<div class="btn search">' + I18n.get('search') + '</div>');
	buttonSearch.click(function() {
		that.loadMonitoring();
	});
	buttonRow.append(buttonSearch);
	
	//collapsibles and tables
	for (var i=0; i<this.availableCollapsibles.length; i++){
		//collapsible type
		var name = this.availableCollapsibles[i].name;
		//add table to collapsible
		this[name].setContent(this[name].table.buildJQ());
		//add collapsible to content
		jQ.append(this[name].buildJQ());
	}
};

MonitoringConsolePage.prototype.displayDetails = function(taskName, taskId) {
	var that = this;
	AjaxManager.getJSON('getMonitoringDetails', {
		'name' : taskName,
		'id' : taskId
	}, function(result) {
		if (result.success) {
			//result.details contains details
			if (Util.checkArray(result.details) && result.details.length > 0){
				var table = new TableModule();
				table.objectMap = new Map();
				table.getJQ().addClass('details');
				$.each(result.details, function(id, value){
					if (id == 0){
						$.each(value, function(key){
							var col = new Column(key, I18n.get('monitoring.console.column.' + key), that.columnSizesMapping[taskName][key], true);
							col.getText = function(val) {
								return (function(v, k){ return $('<span class="pop-over">'+ I18n.get("" + v[k], true) +'</span>').click(function(){
									$('#cell-details-title').show();
									$('#cell-details').show().text($(this).text());
								});})(val, key);
							};
							col.getAlt = function(val) {
								return (function(v, k){ return I18n.get("" + v[k], true); })(val, key);
							};
							table.columnList.push(col);
						});
					}
					table.objectMap.put(table.objectMap.size, value);
				});
				var popupContent = $('<div/>');
				popupContent.append(table.buildJQ());
				popupContent.append('<div id="cell-details-title" style="width:100%;text-align:left;margin-left:10px;display:none;">' + I18n.get('monitoring.console.cellDetails') + '</div>');
				popupContent.append($('<div id="cell-details" class="cell-details"></div>'));
				PopupModule.getInstance().show({
					'title' : I18n.get('monitoring.console.details') + ' ' + taskId + ' (' + I18n.get('monitoring.console.' + taskName) + ')',
					'content' : popupContent,
					'button0' : { 'text' : 'OK' }
				});
			} else {
				PopupModule.getInstance().show({
					'title' : I18n.get('monitoring.console.noDetailsT'),
					'content' : I18n.get('monitoring.console.noDetails'),
					'button0' : { 'text' : 'OK' }
				});
			}
		}
	});
};

MonitoringConsolePage.prototype.loadMonitoring = function(callback) {
	if (!Util.checkFunction(callback) || (Util.checkFunction(callback) && this.monitoringLoaded == false)){
		var that = this;
		AjaxManager.getJSON('getMonitoringConsole', {
			'startDate' : this.inputBeginDate.getMillis(),
			'endDate' : this.inputEndDate.getMillis(),
			'referrerId' : this.inputReferrer.value.id,
			'status' : this.inputStatus.value,
			'id' : this.inputId.value,
			'name' : this.inputName.value
		}, function(result) {
			if (result.success) {
				if (result.tasks.size == 0){
					if (!Util.checkFunction(callback)){
						PopupModule.getInstance().show({
							'title' : I18n.get('monitoring.console.noResultT'),
							'content' : I18n.get('monitoring.console.noResult'),
							'button0' : { 'text' : 'OK' }
						});
					}
				}
				//fill each collapsible
				for (var n = 0; n<that.availableCollapsibles.length; n++){
					var name = that.availableCollapsibles[n].name;
					var table = that[name].table;
					table.objectMap = new Map();
					//fill the correponding map
					var list = result.tasks[name];
					if (Util.checkArray(list)){
						for (var i = 0; i < list.length; i++) {
							table.objectMap.put(table.objectMap.size, list[i]);
						}
						table.objectMap.sort('startDate', true);
						//if search button is pressed, uncollapse where results have been found
						if (!Util.checkFunction(callback)){
							if (list.length > 0) {
								that[name].uncollapse();
							} else {
								that[name].collapse();
							}
						}
					} else {
						that[name].collapse();
					}
					table.buildJQ();
				}
			} else {
				console.error('Failed to load monitoring [referrerId=' + that.inputReferrer.value.id + ']');
			}
			Util.getFunction(callback)();
		});
		this.monitoringLoaded = true;
	} else {
		Util.getFunction(callback)();
	}
};
